package com.tgy.crud.handler;

import com.tgy.crud.common.CommonResult;
import com.tgy.crud.common.ResultCode;
import com.tgy.crud.exception.CrudException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {



    @ExceptionHandler(Exception.class)
    public String handleException(HttpServletRequest request, Exception e){

        /**
         * 处理异常
         */
        log.error(e.getMessage());
        if (e instanceof CrudException){

            CrudException crudException = (CrudException)e;
            ResultCode code = crudException.getCode();

            request.setAttribute("result", CommonResult.failed(code));
            request.setAttribute("javax.servlet.error.status_code",code.getCode());

        }else if (e instanceof ConstraintViolationException) {

            ConstraintViolationException e1 = (ConstraintViolationException) e;

            log.info(e1.getMessage());

        }else if(e instanceof MethodArgumentNotValidException) {

            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException) e;

            log.info(e1.getMessage());
        }
//        }else {
//
//            request.setAttribute("result",CommonResult.systemError());
//            request.setAttribute("javax.servlet.error.status_code",ResultCode.SYSTEMERROR.getCode());
//        }

        request.setAttribute("result",CommonResult.systemError());
        request.setAttribute("javax.servlet.error.status_code",ResultCode.SYSTEMERROR.getCode());

        return "forward:/error";
    }
}
